package part2;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;

public class Serveur {

    ServerSocket serverSocket = null;
    ServerSocket server;
    Socket connectSocket = null;
    String data = "Hello from UDP SERVER";
    InetAddress clientIP;
    int clientPort;
    int portNumber = 1025;
    String fileName;

    public Serveur(int portNumber) {

	this.portNumber = portNumber;

	// Ouvrir une socket serveur
	try {
	    this.serverSocket = new ServerSocket(portNumber);
	} catch (IOException e) {
	    System.out.println(e);
	}

	attenteConnexion();
    }

    // Creer un objet pour le socket de connexion
    public void attenteConnexion() {
	try {
	    while (true) {
		System.out.println("Serveur en attente d'une connexion");
		connectSocket = serverSocket.accept();
		//read();
		Runnable req = new RequeteServeur(connectSocket);
		Thread thr = new Thread(req);
		thr.start();
		Thread.sleep(100);
	    }
	} catch (IOException e) {
	    System.out.println(e);
	} catch (InterruptedException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    public void read() {
	int MAXLENGTH = 256;
	byte[] buff = new byte[MAXLENGTH];
	try {
	    InputStream in = connectSocket.getInputStream();
	    // On recoit le message du client
	    in.read(buff);
	    String message = new String(buff);

	    System.out.println("Message en provenance du Client: "
		    + new String(buff));
	    String[] result = message.split("\\s");
	    if (result[0].equals("GET")) {
		if (result[1].startsWith("/") == true) {
		    fileName = result[1].substring(1);
		} else {
		    fileName = result[1];
		}
		File file = new File(fileName);
		FileInputStream inFile = new FileInputStream(fileName);
		byte[] fileInBytes = new byte[(int) file.length()];
		inFile.read(fileInBytes);
		sendToClient(
			new DataOutputStream(connectSocket.getOutputStream()),
			fileInBytes, (int) file.length());
	    }
	} catch (IOException e) {
	    System.out.println(e);
	}
    }

    public void sendToClient(DataOutputStream out, byte[] message,
	    int numOfBytes) {
	try {
	    out.writeBytes("HTTP/1.0 200 Document Follows\r\n");
	    if (fileName.endsWith(".jpg"))
		out.writeBytes("Content-Type:image/jpeg\r\n");
	    if (fileName.endsWith(".gif"))
		out.writeBytes("Content-Type:image/gif\r\n");
	    if (fileName.endsWith(".png"))
		out.writeBytes("Content-Type:image/png\r\n");
	    out.writeBytes("Content-Length: " + message.length + "\r\n");
	    out.writeBytes("\r\n");
	    out.write(message, 0, numOfBytes);
	    connectSocket.close();

	} catch (IOException e) {
	    System.out.println("Erreur dans la methode sendToClient");
	}

    }

    // Fermer le socket
    public void fermerConnexion() {
	try {
	    connectSocket.close(); // Close the socket. We are
	    // done with this client!
	    serverSocket.close(); // close the serverSocket socket
	    server.close(); // close server as well
	} catch (IOException e) {
	    System.out.println(e);
	}

    }

}